package com.easy.order.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easy.common.bean.OrderItem;
import com.easy.common.service.OrderItemService;
import com.easy.order.mapper.OrderItemMapper;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
@DubboService
public class OrderItemServiceImpl extends ServiceImpl<OrderItemMapper, OrderItem> implements OrderItemService {
    // 日志对象：便于排查软删除、查询等操作的结果
    private static final Logger log = LoggerFactory.getLogger(OrderItemServiceImpl.class);


    @Override
    public OrderItem getOrderItemById(Integer id) {
        if (id == null) {
            log.warn("查询子订单失败：ID为空");
            return null;
        }
        // MP自动追加条件：WHERE id=? AND isdel=0
        return super.getById(id);
    }

    @Override
    public OrderItem getOrderItemByName(String productName) {
        if (productName == null || productName.trim().isEmpty()) {
            log.warn("查询子订单失败：商品名称为空");
            return null;
        }
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("product_name", productName.trim()) // 子订单表的商品名字段
                .eq("isdel", 0); // MP会自动加，显式写更清晰（避免配置遗漏导致查已删数据）
        return baseMapper.selectOne(queryWrapper);
    }

    @Override
    public int addOrderItem(OrderItem orderItem) {
        if (orderItem == null) {
            log.warn("新增子订单失败：子订单对象为空");
            return 0;
        }
        LocalDateTime now = LocalDateTime.now();
        orderItem.setCreateTime(now);
        orderItem.setUpdateTime(now);
        // 核心：新增子订单默认“未删除”（isdel=0）
        orderItem.setIsdel(0);

        // 校验子订单核心关联字段（避免无效数据）
        if (orderItem.getOrderId() == null || orderItem.getProductId() == null || orderItem.getQuantity() == null) {
            log.error("新增子订单失败：核心字段（关联总订单ID/商品ID/购买数量）缺失");
            return 0;
        }

        boolean isSuccess = super.save(orderItem);
        log.info("新增子订单{}：子订单ID={}，关联总订单ID={}",
                isSuccess ? "成功" : "失败",
                orderItem.getId(),
                orderItem.getOrderId());
        return isSuccess ? 1 : 0;
    }

    @Override
    public int updateOrderItem(OrderItem orderItem) {
        if (orderItem.getId() == null) {
            log.warn("更新子订单失败：子订单ID为空");
            return 0;
        }
        // 校验子订单是否存在且未删（避免更新已删除的记录）
        if (getOrderItemById(orderItem.getId()) == null) {
            log.warn("更新子订单失败：ID={}的子订单不存在或已删除", orderItem.getId());
            return 0;
        }
        // 更新时间戳
        orderItem.setUpdateTime(LocalDateTime.now());
        // MP自动追加条件：UPDATE ... WHERE id=? AND isdel=0
        boolean isSuccess = super.updateById(orderItem);
        return isSuccess ? 1 : 0;
    }
    @Override
    public int deleteOrderItem(Integer id) {
        if (id == null) {
            log.warn("软删除子订单失败：子订单ID为空");
            return 0;
        }
        // 校验子订单是否存在且未删（避免重复删除）
        if (getOrderItemById(id) == null) {
            log.warn("软删除子订单失败：ID={}的子订单不存在或已删除", id);
            return 0;
        }

        // 核心：MP自动执行软删除SQL，而非物理删除
        // 实际SQL：UPDATE order_item SET isdel=1, update_time=? WHERE id=? AND isdel=0
        boolean isSuccess = super.removeById(id);
        log.info("软删除子订单{}：子订单ID={}", isSuccess ? "成功" : "失败", id);
        return isSuccess ? 1 : 0;
    }
    @Override
    public List<OrderItem> getAll(OrderItem orderItem) {
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isdel", 0); // 强制过滤已删数据

        // 子订单真实字段条件（order_id/product_id/seckill_activity_id均为子订单表字段，无需修改）
        if (orderItem.getOrderId() != null) {
            queryWrapper.eq("order_id", orderItem.getOrderId()); // 按关联总订单ID查
        }
        if (orderItem.getProductId() != null) {
            queryWrapper.eq("product_id", orderItem.getProductId()); // 按商品ID查
        }
        if (orderItem.getSeckillActivityId() != null) {
            queryWrapper.eq("seckill_activity_id", orderItem.getSeckillActivityId()); // 按秒杀活动ID查
        }
        if (orderItem.getOrderNo() != null && !orderItem.getOrderNo().trim().isEmpty()) {
            queryWrapper.eq("order_no", orderItem.getOrderNo().trim()); // 按订单编号查（补充）
        }

        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public IPage<OrderItem> getPage(OrderItem orderItem, IPage<OrderItem> page) {
        if (page == null) {
            log.warn("分页查询子订单失败：分页参数为空");
            return null;
        }
        QueryWrapper<OrderItem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("isdel", 0); // 自动过滤已删

        // 分页筛选条件（子订单真实字段，无需修改）
        if (orderItem.getOrderNo() != null && !orderItem.getOrderNo().trim().isEmpty()) {
            queryWrapper.like("order_no", orderItem.getOrderNo().trim()); // 订单编号模糊查
        }
        if (orderItem.getProductName() != null && !orderItem.getProductName().trim().isEmpty()) {
            queryWrapper.like("product_name", orderItem.getProductName().trim()); // 商品名称模糊查
        }
        if (orderItem.getOrderId() != null) {
            queryWrapper.eq("order_id", orderItem.getOrderId()); // 补充：按关联总订单ID分页查
        }

        // MP自动处理分页+软删除过滤
        return baseMapper.selectPage(page, queryWrapper);
    }
}